import React, { useReducer } from "react";

const defaultState = {
  count: 5,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return {
        ...state,
        count: state.count + 1,
      };
    case "decrement":
      return {
        ...state,
        count: state.count - 1,
      };
    default:
      return state;
  }
};

const App = () => {
  // useReducer调用的时候可以接受两个参数,分别是reducer函数以及state的初始值
  // useReducer会有一个返回值，返回值是一个数组, 分别是state以及dispatch
  const [state, dispatch] = useReducer(reducer, defaultState);
  return (
    <>
      <h2>useReducer</h2>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
};

export default App;
